#!/usr/bin/env node
/**
 *
 * Just a small util to run a hardhat script for all networks
 *
 * Usage: scripts/all_networks run scripts/etc...
 * Usage: scripts/all_networks unlock:info
 */

const allNetworks = require('@unlock-protocol/networks')
const { execSync } = require('child_process')

// if any network is present this array, only these will be executed
const only = []

// these networks will be excluded from run
const toExclude = ['localhost', 'default', 'networks']
const excludeTestnets = false

const networks = only.length
  ? only
  : Object.keys(allNetworks).filter(
    (n) =>
      !toExclude.includes(n) &&
      (excludeTestnets ? !allNetworks[n].isTestNetwork : true)
  )

console.log(`Running task for the following networks: ${networks.toString()}`)

for (let i = 0; i < networks.length; i++) {
  const cmd = `yarn hardhat`
  const args = ['--network', networks[i], ...process.argv.slice(2)]

  console.log(cmd, args)
  try {
    execSync(`${cmd} ${args.join(' ')}`, {
      stdio: 'inherit',
    })
  } catch (error) {
    console.log(`Network ${networks[i]} failed`)
    console.log(error.message)
  }
}
